#!/bin/bash

# Smart Snapshotter Benchmark Script
# This script runs comprehensive benchmarks for the smart snapshotter project

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Default values
BENCH_TIME="1s"
BENCH_COUNT=1
BENCH_CPU=""
BENCH_MEM="true"
OUTPUT_DIR="benchmark_results"
PACKAGE="./..."

# Function to print colored output
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to show usage
usage() {
    cat << EOF
Usage: $0 [OPTIONS]

Run benchmarks for smart snapshotter

OPTIONS:
    -t, --time TIME         Benchmark time per test (default: 1s)
    -c, --count COUNT       Number of iterations (default: 1)
    -p, --package PACKAGE   Package to benchmark (default: ./...)
    -o, --output DIR        Output directory for results (default: benchmark_results)
    --cpu CPU               CPU profile settings
    --no-mem                Disable memory profiling
    -h, --help              Show this help message

EXAMPLES:
    $0                      # Run all benchmarks with default settings
    $0 -t 5s -c 3           # Run benchmarks for 5 seconds, 3 iterations
    $0 -p ./pkg/dedup       # Benchmark only dedup package
    $0 --cpu 1,2,4          # Run with CPU profiling for 1, 2, and 4 CPUs

EOF
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -t|--time)
            BENCH_TIME="$2"
            shift 2
            ;;
        -c|--count)
            BENCH_COUNT="$2"
            shift 2
            ;;
        -p|--package)
            PACKAGE="$2"
            shift 2
            ;;
        -o|--output)
            OUTPUT_DIR="$2"
            shift 2
            ;;
        --cpu)
            BENCH_CPU="$2"
            shift 2
            ;;
        --no-mem)
            BENCH_MEM="false"
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            usage
            exit 1
            ;;
    esac
done

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Get current timestamp for result files
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")

print_info "Starting benchmark run at $(date)"
print_info "Configuration:"
echo "  Package: $PACKAGE"
echo "  Benchmark time: $BENCH_TIME"
echo "  Iterations: $BENCH_COUNT"
echo "  Output directory: $OUTPUT_DIR"
echo "  Memory profiling: $BENCH_MEM"
if [[ -n "$BENCH_CPU" ]]; then
    echo "  CPU profiling: $BENCH_CPU"
fi

# Build benchmark command
BENCH_CMD="go test -bench=. -benchtime=$BENCH_TIME -count=$BENCH_COUNT"

if [[ "$BENCH_MEM" == "true" ]]; then
    BENCH_CMD="$BENCH_CMD -benchmem"
fi

if [[ -n "$BENCH_CPU" ]]; then
    BENCH_CMD="$BENCH_CMD -cpu=$BENCH_CPU"
fi

# Add output formatting
BENCH_CMD="$BENCH_CMD -benchtime=1s"

# Run benchmarks and capture output
print_info "Running benchmarks..."
BENCH_OUTPUT_FILE="$OUTPUT_DIR/benchmark_${TIMESTAMP}.txt"
BENCH_JSON_FILE="$OUTPUT_DIR/benchmark_${TIMESTAMP}.json"

# Run benchmarks with JSON output for analysis
if go test -bench=. -json $PACKAGE 2>/dev/null | tee "$BENCH_JSON_FILE" | grep -E "(Benchmark|PASS|FAIL)"; then
    print_info "Benchmarks completed successfully"
else
    print_error "Benchmarks failed"
    exit 1
fi

# Run the main benchmark command
print_info "Running detailed benchmarks..."
if $BENCH_CMD $PACKAGE 2>&1 | tee "$BENCH_OUTPUT_FILE"; then
    print_info "Detailed benchmarks completed successfully"
else
    print_error "Detailed benchmarks failed"
    exit 1
fi

# Generate summary report
SUMMARY_FILE="$OUTPUT_DIR/benchmark_summary_${TIMESTAMP}.txt"
print_info "Generating summary report..."

cat > "$SUMMARY_FILE" << EOF
Smart Snapshotter Benchmark Summary
====================================
Date: $(date)
Package: $PACKAGE
Benchmark Time: $BENCH_TIME
Iterations: $BENCH_COUNT

Results Summary:
EOF

# Extract key metrics from benchmark output
grep -E "Benchmark.*\d+\s+\d+\s+\d+\s+\d+" "$BENCH_OUTPUT_FILE" | while read line; do
    echo "  $line" >> "$SUMMARY_FILE"
done

echo "" >> "$SUMMARY_FILE"
echo "Top 5 Fastest Operations:" >> "$SUMMARY_FILE"
grep -E "Benchmark.*\d+\s+\d+\s+\d+\s+\d+" "$BENCH_OUTPUT_FILE" | sort -k3 -n | head -5 | while read line; do
    echo "  $line" >> "$SUMMARY_FILE"
done

echo "" >> "$SUMMARY_FILE"
echo "Top 5 Slowest Operations:" >> "$SUMMARY_FILE"
grep -E "Benchmark.*\d+\s+\d+\s+\d+\s+\d+" "$BENCH_OUTPUT_FILE" | sort -k3 -nr | head -5 | while read line; do
    echo "  $line" >> "$SUMMARY_FILE"
done

# Run specific component benchmarks if requested
if [[ "$PACKAGE" == "./..." ]]; then
    print_info "Running component-specific benchmarks..."

    # Deduplication benchmarks
    print_info "Running deduplication benchmarks..."
    DEDUP_FILE="$OUTPUT_DIR/dedup_benchmark_${TIMESTAMP}.txt"
    if go test -bench=BenchmarkDedup -benchmem -benchtime=$BENCH_TIME ./pkg/dedup 2>&1 | tee "$DEDUP_FILE"; then
        print_info "Deduplication benchmarks completed"
    else
        print_warn "Deduplication benchmarks failed"
    fi

    # Cache benchmarks
    print_info "Running cache benchmarks..."
    CACHE_FILE="$OUTPUT_DIR/cache_benchmark_${TIMESTAMP}.txt"
    if go test -bench=BenchmarkCache -benchmem -benchtime=$BENCH_TIME ./pkg/cache 2>&1 | tee "$CACHE_FILE"; then
        print_info "Cache benchmarks completed"
    else
        print_warn "Cache benchmarks failed"
    fi
fi

# Generate performance comparison if previous results exist
if [[ -f "$OUTPUT_DIR/benchmark_summary_"*.txt && $(ls -1 "$OUTPUT_DIR"/benchmark_summary_*.txt 2>/dev/null | wc -l) -gt 1 ]]; then
    print_info "Generating performance comparison..."
    COMPARISON_FILE="$OUTPUT_DIR/performance_comparison_${TIMESTAMP}.txt"

    cat > "$COMPARISON_FILE" << EOF
Performance Comparison
=====================

Generated on: $(date)

EOF

    # Compare with previous runs
    PREVIOUS_SUMMARY=$(ls -1t "$OUTPUT_DIR"/benchmark_summary_*.txt | head -2 | tail -1)
    echo "Comparing with: $PREVIOUS_SUMMARY" >> "$COMPARISON_FILE"
    echo "" >> "$COMPARISON_FILE"

    # Simple comparison logic (can be enhanced)
    echo "Key differences:" >> "$COMPARISON_FILE"
    echo "  (Manual analysis required for detailed comparison)" >> "$COMPARISON_FILE"
fi

print_info "Benchmark run completed successfully!"
print_info "Results saved to:"
echo "  Summary: $SUMMARY_FILE"
echo "  Detailed output: $BENCH_OUTPUT_FILE"
echo "  JSON data: $BENCH_JSON_FILE"
if [[ -f "$DEDUP_FILE" ]]; then
    echo "  Deduplication: $DEDUP_FILE"
fi
if [[ -f "$CACHE_FILE" ]]; then
    echo "  Cache: $CACHE_FILE"
fi
if [[ -f "$COMPARISON_FILE" ]]; then
    echo "  Comparison: $COMPARISON_FILE"
fi

print_info "To view the summary:"
echo "  cat $SUMMARY_FILE"
print_info "To view detailed results:"
echo "  less $BENCH_OUTPUT_FILE"